import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2btrailer/b2btrailermodel.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class B2BTrailerSelfpickupSubmitScreen extends StatelessWidget {
  B2bTrailerQr data;

  B2BTrailerSelfpickupSubmitScreen({this.data});

  @override
  Widget build(BuildContext context) {
    return B2BTrailerSelfpickupSubmitScreenPage(data: data);
  }
}

class B2BTrailerSelfpickupSubmitScreenPage extends StatefulWidget {
  B2bTrailerQr data;

  B2BTrailerSelfpickupSubmitScreenPage({this.data});

  @override
  _B2BTrailerSelfpickupSubmitScreenPageState createState() => _B2BTrailerSelfpickupSubmitScreenPageState(b2bTrailerQr: data);
}

class _B2BTrailerSelfpickupSubmitScreenPageState extends BaseState<B2BTrailerSelfpickupSubmitScreenPage> {
  B2bTrailerQr b2bTrailerQr;

  _B2BTrailerSelfpickupSubmitScreenPageState({this.b2bTrailerQr});

  int index = 0, position;

  final controller = ScrollController();

  PhotoBean sealPhoto = new PhotoBean();
  PhotoBean goodsPhoto = new PhotoBean();
  PhotoBean afterLoadingPhoto = new PhotoBean();
  List<PhotoBean> bols = new List();

  bool layoutPalletTag = false;
  String tvPallet;

  @override
  String setTitle({String title}) {
    return "Trailer: Submit";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
      bols.add(new PhotoBean());
    });
    printPalletTag();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "Order#: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 13.0),
              ),
              Expanded(
                child: Text(
                  "(${Utils.getStringisEmpty(b2bTrailerQr.refId)})${Utils.getStringisEmpty(b2bTrailerQr.jobId)}",
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 13.0),
                ),
              ),
            ],
          ),
          Expanded(
            flex: 1, //设置权重
            child: SingleChildScrollView(
              controller: controller, // 设置控制器
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: setPhotoView("Seal #", 0, sealPhoto),
                      ),
                      Expanded(
                        flex: 1,
                        child: setPhotoView("Goods", 1, goodsPhoto),
                      ),
                      Expanded(
                        flex: 1,
                        child: setPhotoView("After Loading", 2, afterLoadingPhoto),
                      ),
                    ],
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: [
                            Text(
                              '*',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                            ),
                            Text(
                              'BOL',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 5,
                        ),
                        Container(
                          height: 70,
                          width: double.infinity,
                          child: setPhotoListView(3, bols),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
              visible: layoutPalletTag,
              child: Row(
                children: [
                  Text(
                    "Pallet Tag: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 13.0),
                  ),
                  Expanded(
                      child: Text(
                    Utils.getStringisEmpty(tvPallet),
                    style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
                  )),
                  GestureDetector(
                    child: SizedBox(
                      height: 35, // 高度
                      child: ElevatedButton(
                        child: Text(
                          "Print",
                          style: TextStyle(color: MyAppTheme.white, fontSize: 14.0),
                        ),
                        style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
                          shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                            ),
                          ),
                        ),
                        onPressed: () {},
                      ),
                    ),
                  )
                ],
              )),
        ],
      ),
    );
  }

  Widget setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          margin: EdgeInsets.only(top: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '*',
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
              ),
              Text(
                hintText,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
              ),
            ],
          ),
        ),
        SizedBox(
          height: 5,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 70,
              height: 70,
              child: Stack(
                children: <Widget>[
                  GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      index = type;
                      ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                    },
                    child: photoBean.image == null
                        ? (photoBean.urlImg == null
                            ? Image.asset(
                                'assets/images/add.png',
                                width: 70,
                                height: 70,
                                fit: BoxFit.cover,
                              )
                            : Image.network(
                                Constants.baseImgUrl + photoBean.urlImg,
                                width: 70,
                                height: 70,
                                fit: BoxFit.cover,
                              ))
                        : Image.file(
                            photoBean.image,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ),
                  ),
                  Visibility(
                    visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                    child: Positioned(
                      top: 2.0,
                      right: 2.0,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            photoBean.urlImg = null;
                            photoBean.image = null;
                          });
                        },
                        child: Image.asset(
                          'assets/images/ic_delete_menu.png',
                          width: 15,
                          height: 15,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  ListView setPhotoListView(int type, List<PhotoBean> data) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PhotoBean photoBean = data[index];
        print(photoBean.toString());
        return Container(
          height: 70,
          width: 70,
          margin: const EdgeInsets.only(left: 0, top: 0, right: 10, bottom: 0),
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  // 请求焦点
                  FocusScope.of(context).requestFocus(FocusNode());
                  this.index = type;
                  this.position = index;
                  ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                },
                child: photoBean.image == null
                    ? (photoBean.urlImg == null
                        ? Image.asset(
                            'assets/images/add.png',
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          )
                        : Image.network(
                            Constants.baseImgUrl + photoBean.urlImg,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ))
                    : Image.file(
                        photoBean.image,
                        width: 70,
                        height: 70,
                        fit: BoxFit.cover,
                      ),
              ),
              Visibility(
                visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                child: Positioned(
                  top: 2.0,
                  left: 53,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        data.removeAt(index);
                      });
                    },
                    child: Image.asset(
                      'assets/images/ic_delete_menu.png',
                      width: 15,
                      height: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      switch (index) {
        case 0:
          sealPhoto.image = image;
          name = "seal";
          break;
        case 1:
          goodsPhoto.image = image;
          name = "goods";
          break;
        case 2:
          afterLoadingPhoto.image = image;
          name = "afterLoading";
          break;
        case 3:
          PhotoBean photoBean = new PhotoBean();
          photoBean.image = image;
          bols.insert(position, photoBean);
          name = "bol";
          break;
      }
      fileUpload(b2bTrailerQr.jobId, "b2bTrailer", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  void setNext() {
    setSubmit();
  }

  void setSubmit() {
    ToastContext().init(context);
    if (DateTime.now().millisecondsSinceEpoch - timeMillis < 1000) {
      return;
    }
    timeMillis = DateTime.now().millisecondsSinceEpoch;

    if ((sealPhoto.image == null) && (sealPhoto.urlImg == null)) {
      Toast.show("Please add seal photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if ((goodsPhoto.image == null) && (goodsPhoto.urlImg == null)) {
      Toast.show("Please add goods photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if ((afterLoadingPhoto.image == null) && (afterLoadingPhoto.urlImg == null)) {
      Toast.show("Please add After Loading photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    if (Utils.isEmpty(sealPhoto.urlImg)) {
      fileUpload(b2bTrailerQr.jobId, "b2bTrailer", sealPhoto.image, "seal", 0, position, true, true);
      return;
    }
    if (Utils.isEmpty(goodsPhoto.urlImg)) {
      fileUpload(b2bTrailerQr.jobId, "b2bTrailer", goodsPhoto.image, "goods", 1, position, true, true);
      return;
    }
    if (Utils.isEmpty(afterLoadingPhoto.urlImg)) {
      fileUpload(b2bTrailerQr.jobId, "b2bTrailer", afterLoadingPhoto.image, "afterLoading", 2, position, true, true);
      return;
    }
    b2bTrailerQr.seal = sealPhoto.urlImg;
    b2bTrailerQr.goods = goodsPhoto.urlImg;
    b2bTrailerQr.closeDoor = afterLoadingPhoto.urlImg;

    if (bols.length < 1) {
      Toast.show("Please add bols photos", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    List<String> bolsTemp = new List();
    for (int i = 0; i < bols.length - 1; i++) {
      PhotoBean photoBean = bols[i];
      if (Utils.isEmpty(photoBean.urlImg)) {
        position = i;
        fileUpload(b2bTrailerQr.jobId, "b2bTrailer", photoBean.image, "bol", 3, position, true, true);
        return;
      }
      bolsTemp.add(photoBean.urlImg);
    }
    b2bTrailerQr.bols = bolsTemp;
    b2bLoadedLpn();
  }

  bool judgeType(String mold, String hint) {
    if (Utils.isEmpty(mold)) {
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }

    if (double.parse(mold) <= 0) {
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }
    return true;
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
    reset();
  }

  void reset() {
    setState(() {
      sealPhoto = new PhotoBean();
      goodsPhoto = new PhotoBean();
      afterLoadingPhoto = new PhotoBean();
      bols = new List();
      bols.add(new PhotoBean());
    });
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    switch (type) {
      case 0:
        sealPhoto.urlImg = path;
        break;
      case 1:
        goodsPhoto.urlImg = path;
        break;
      case 2:
        afterLoadingPhoto.urlImg = path;
        break;
      case 3:
        bols[position].urlImg = path;
        break;
    }

    if (isSubmit) {
      setSubmit();
    }
  }

  void printPalletTag() async {
    updateHint('');

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.printPalletTag + "/" + b2bTrailerQr.jobId);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200 || baseResponse.status == 9605) {
      setState(() {
        textEditingController.text = "";
        PalletTagPrint palletTagPrint = PalletTagPrint.fromJson(baseResponse.data);
        if (palletTagPrint == null) {
          layoutPalletTag = false;
        } else {
          layoutPalletTag = true;
          tvPallet = palletTagPrint.fileName;
        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void b2bLoadedLpn() async {
    updateHint('');

    String json = jsonEncode(b2bTrailerQr);

    // 显示加载中对话框
    LoadingIndicator.show(context, title: "submit...");

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.b2bLoadedLpn, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      // List<TrailerOBLPN> loadedLpns = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TrailerOBLPN.fromJson(userJson)).toList());
      // Navigator.of(context).pop(loadedLpns);
      Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
